package com.googlecode.yoohoo.xmppcore.protocol;

import com.googlecode.yoohoo.xmppcore.protocol.translation.ITranslator;
import com.googlecode.yoohoo.xmppcore.protocol.translation.IXmlWriter;
import com.googlecode.yoohoo.xmppcore.protocol.translation.XmlWriter;

public abstract class AbstractError implements IError {
	protected String definedCondition;
	protected XmlLangText text;
	protected Object applicationSpecificCondition;
	
	public AbstractError() {
	}
	
	public AbstractError(String definedCondition) {
		this(definedCondition, null);
	}
	
	public AbstractError(String definedCondition, XmlLangText text) {
		this.definedCondition = definedCondition;
		this.text = text;
	}
	
	@Override
	public String getDefinedCondition() {
		return definedCondition;
	}

	@Override
	public void setDefinedCondition(String definedCondition) {
		this.definedCondition = definedCondition;
	}

	@Override
	public XmlLangText getText() {
		return text;
	}

	@Override
	public void setText(XmlLangText text) {
		this.text = text;
	}

	@Override
	public Object getApplicationSpecificCondition() {
		return applicationSpecificCondition;
	}

	@Override
	public void setApplicationSpecificCondition(Object applicationSpecificCondition) {
		this.applicationSpecificCondition = applicationSpecificCondition;
	}
	
	@Override
	public String toXml() {
		IXmlWriter writer = new XmlWriter();
		
		writeErrorHeader(writer);
		
		writer.writeStartElement(definedCondition);
		writer.writeNamespace(getDefinedConditionNamespace());
		writer.writeEndElement();
		
		if (text != null && !"".equals(text.getText())) {
			writer.writeStartElement("text");
			if (text.getXmlLang() != null) {
				writer.writeAttribute("xml:lang", text.getXmlLang());
			}
			writer.writeNamespace(getDefinedConditionNamespace());
			writer.writeCharacters(text.getText());
			writer.writeEndElement();
		}
		
		if (applicationSpecificCondition != null && applicationSpecificCondition instanceof ITranslator) {
			ITranslator translator = (ITranslator)applicationSpecificCondition;
			writer.writeCharacters(translator.toXml(), false);
		}
		
		writeErrorFooter(writer);

		return writer.toXml();
	}

	protected abstract void writeErrorHeader(IXmlWriter writer);
	protected abstract void writeErrorFooter(IXmlWriter writer);
	protected abstract String getDefinedConditionNamespace();
}
